import React, { useEffect, useState, useRef } from 'react'
import { NavBar, Toast, SpinLoading, Button, List } from 'antd-mobile'
import { useNavigate, useParams, useLocation } from 'react-router-dom'
import { getDoctorInfo, followDoctor, cancelFollowDoctor, type DoctorInfo, type DoctorGift, type DoctorComment } from '../../api/doctor'
import { useSelector } from 'react-redux'
import type { RootState } from '../../store/types'
import { hasPermission } from '../../utils/permission'
import './index.css'

function DoctorDetail() {
  const navigate = useNavigate()
  const location = useLocation()
  const { doctorId } = useParams<{ doctorId: string }>()
  const userEmail = useSelector((state: RootState) => state.info.email)
  
  // 优先使用传递过来的医生信息
  const passedDoctorInfo = location.state?.doctorInfo
  const [doctorInfo, setDoctorInfo] = useState<DoctorInfo | null>(passedDoctorInfo || null)
  const [loading, setLoading] = useState(!passedDoctorInfo)
  const [isSticky, setIsSticky] = useState(false)
  const stickyRef = useRef<HTMLDivElement>(null)
  const [isFollowed, setIsFollowed] = useState(false)

  // 返回上一页
  const handleBack = () => {
    navigate(-1)
  }

  // 获取医生详情信息
  const fetchDoctorInfo = async () => {
    // 如果已经有传递过来的医生信息，直接使用
    if (passedDoctorInfo) {
      const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
      const shouldFollow = passedDoctorInfo.followFlag === 1 || followedDoctors.includes(passedDoctorInfo.doctorId)
      setIsFollowed(shouldFollow)
      setDoctorInfo(passedDoctorInfo)
      setLoading(false)
      return
    }

    if (!doctorId) {
      Toast.show({ content: '医生ID不存在' })
      return
    }

    try {
      setLoading(true)
      const response = await getDoctorInfo(parseInt(doctorId))
      if (response.status === '0000') {
        // 获取本地存储的关注状态
        const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
        const doctorData = response.result
        
        // 如果API没有返回关注状态，从本地存储恢复
        if (doctorData.followFlag === undefined || doctorData.followFlag === null) {
          doctorData.followFlag = followedDoctors.includes(doctorData.doctorId) ? 1 : 0
        }
        
        // 设置关注状态
        const shouldFollow = doctorData.followFlag === 1
        setIsFollowed(shouldFollow)
        setDoctorInfo(doctorData)
      } else {
        Toast.show({ content: response.message || '获取医生信息失败' })
      }
    } catch (error) {
      console.error('获取医生信息失败:', error)
      Toast.show({ content: '网络错误，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 格式化时间
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  // 关注/取消关注医生
  const handleFollow = async () => {
    if (!doctorInfo) return
    
    try {
      if (isFollowed) {
        // 取消关注
        const response = await cancelFollowDoctor(doctorInfo.doctorId)
        if (response.status === '0000') {
          Toast.show({ content: response.message || '取消关注成功' })
          setIsFollowed(false)
          // 更新本地存储
          const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
          const updatedFollowedDoctors = followedDoctors.filter((id: number) => id !== doctorInfo.doctorId)
          localStorage.setItem('followedDoctors', JSON.stringify(updatedFollowedDoctors))
        } else {
          Toast.show({ content: response.message || '取消关注失败' })
        }
      } else {
        // 关注
        const response = await followDoctor(doctorInfo.doctorId)
        if (response.status === '0000') {
          Toast.show({ content: response.message || '关注成功' })
          setIsFollowed(true)
          // 更新本地存储
          const followedDoctors = JSON.parse(localStorage.getItem('followedDoctors') || '[]')
          if (!followedDoctors.includes(doctorInfo.doctorId)) {
            followedDoctors.push(doctorInfo.doctorId)
            localStorage.setItem('followedDoctors', JSON.stringify(followedDoctors))
          }
        } else {
          Toast.show({ content: response.message || '关注失败' })
          console.error('handleFollow: 关注API失败，状态码:', response.status, '消息:', response.message)
        }
      }
    } catch (error) {
      console.error('关注操作失败:', error)
      Toast.show({ content: '网络错误，请重试' })
        }
  }

  // 在线问诊
  const handleConsultation = () => {
    // 权限检查已经在PermissionGuard中完成，这里直接执行功能
    Toast.show({ content: '在线问诊功能开发中' })
  }

  // 监听滚动事件，实现吸顶效果
  useEffect(() => {
    const handleScroll = () => {
      if (stickyRef.current) {
        const rect = stickyRef.current.getBoundingClientRect()
        setIsSticky(rect.top <= 0)
      }
    }

    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  useEffect(() => {
    fetchDoctorInfo()
  }, [doctorId])

  if (loading) {
    return (
      <div className="doctor-detail-loading">
        <SpinLoading color="primary" />
        <p>加载中...</p>
      </div>
    )
  }

  if (!doctorInfo) {
    return (
      <div className="doctor-detail-error">
        <p>医生信息不存在</p>
        <Button onClick={handleBack}>返回</Button>
      </div>
    )
  }

  return (
    <div className="doctor-detail-container">
      {/* 头部导航栏 */}
      <NavBar onBack={handleBack} className="doctor-detail-navbar">
        医生详情
      </NavBar>

      {/* 吸顶导航 */}
      <div className={`sticky-nav ${isSticky ? 'sticky' : ''}`}>
        <div className="sticky-nav-content">
          <div className="sticky-doctor-info">
                         <img
               src={doctorInfo?.imagePic || (() => {
                 // 如果医生没有头像，从头像池中获取一个
                 try {
                   const raw = localStorage.getItem('doctorAvatarPool') || '[]'
                   const list = JSON.parse(raw)
                   const avatarPool = Array.isArray(list) ? list : []
                   return avatarPool[0] || '/doctor-default.svg'
                 } catch { 
                   return '/doctor-default.svg'
                 }
               })()}
               alt={doctorInfo?.doctorName}
               onError={(e) => {
                 (e.target as HTMLImageElement).src = '/doctor-default.svg'
               }}
             />
            <div className="sticky-doctor-details">
              <div className="sticky-doctor-name">{doctorInfo?.doctorName}</div>
              <div className="sticky-doctor-title">{doctorInfo?.jobTitle}</div>
            </div>
          </div>
          <Button 
            color="primary" 
            size="small"
            onClick={() => {
              // 检查权限，如果没有权限则提示
              if (!userEmail) {
                Toast.show('请先登录')
                return
              }
              if (!hasPermission(userEmail, 'consultation')) {
                Toast.show('暂无权限，无法在线咨询')
                return
              }
              handleConsultation()
            }}
          >
            立即咨询
          </Button>
        </div>
      </div>

      {/* 医生基本信息 */}
      <div className="doctor-basic-info" ref={stickyRef}>
        <div className="doctor-header">
          <div className="doctor-avatar">
            <img
              src={doctorInfo.imagePic || (() => {
                // 如果医生没有头像，从头像池中获取一个
                try {
                  const raw = localStorage.getItem('doctorAvatarPool') || '[]'
                  const list = JSON.parse(raw)
                  const avatarPool = Array.isArray(list) ? list : []
                  return avatarPool[0] || '/doctor-default.svg'
                } catch { 
                  return '/doctor-default.svg'
                }
              })()}
              alt={doctorInfo.doctorName}
              onError={(e) => {
                (e.target as HTMLImageElement).src = '/doctor-default.svg'
              }}
            />
          </div>
                     <div className="doctor-info">
             <div className="doctor-name-box">
               {doctorInfo.doctorName || '未知医生'}
             </div>
             <p className="doctor-title">{doctorInfo.jobTitle}</p>
             <p className="doctor-hospital">{doctorInfo.inauguralHospital}</p>
             <p className="doctor-experience">从医经验：{doctorInfo.serverNum > 0 ? `${doctorInfo.serverNum}年` : '经验丰富'}</p>
             <div className="doctor-stats">
               <span className="praise-rate">好评率 {doctorInfo.praise}%</span>
               <span className="service-count">服务 {doctorInfo.serverNum} 人</span>
             </div>
           </div>
                                 <div className="doctor-actions">
              <Button 
                size="small" 
                color={isFollowed ? 'default' : 'primary'}
                onClick={() => {
                  // 检查权限，如果没有权限则提示
                  if (!userEmail) {
                    Toast.show('请先登录')
                    return
                  }
                                if (!hasPermission(userEmail, 'follow')) {
                Toast.show('暂无权限，无法关注')
                return
              }
                  handleFollow()
                }}
                style={{
                  backgroundColor: isFollowed ? '#f5f5f5' : undefined,
                  color: isFollowed ? '#999' : undefined,
                  borderColor: isFollowed ? '#d9d9d9' : undefined
                }}
              >
                {isFollowed ? '已关注' : '关注'}
              </Button>
            </div>
        </div>
        
        <div className="doctor-price-section">
          <span className="price-label">咨询价格</span>
          <span className="price-value">¥{doctorInfo.servicePrice}</span>
          <Button 
            color="primary" 
            size="small"
            onClick={() => {
              // 检查权限，如果没有权限则提示
              if (!userEmail) {
                Toast.show('请先登录')
                return
              }
              if (!hasPermission(userEmail, 'consultation')) {
                Toast.show('暂无权限，无法在线咨询')
                return
              }
              handleConsultation()
            }}
            className="consultation-btn"
          >
            立即咨询
          </Button>
        </div>
      </div>

      {/* 医生公告 */}
      <div className="info-section notice-bar">
        <div className="notice-left">📢 医生公告</div>
        <div className="notice-right">医生号源每日凌晨1点自动放号，请合理安排</div>
      </div>

      {/* 排班信息（示意渲染，可替换为真实接口） */}
      <div className="info-section schedule-section">
        <div className="schedule-header">
          <div className="schedule-title">{doctorInfo.inauguralHospital ? doctorInfo.inauguralHospital : '门诊外一科'}</div>
          <div className="schedule-fee">挂号费：<span className="fee">¥ {(() => {
            const raw = Number(doctorInfo.servicePrice) || 0
            const display = raw > 0 ? Math.min(raw, 20) : 20
            return display.toFixed(2)
          })()}</span></div>
        </div>

        <div className="schedule-list">
          {[
            { date: '2020-01-27', week: '周一', time: '上午', remain: 5, tag: '今日' },
            { date: '2020-01-27', week: '周一', time: '下午', remain: 15, tag: '今日' },
            { date: '2020-01-28', week: '周二', time: '上午', remain: 10, tag: '1天后' },
            { date: '2020-01-28', week: '周二', time: '下午', remain: 0, tag: '1天后' },
            { date: '2020-01-29', week: '周三', time: '上午', remain: 10, tag: '2天后' }
          ].map((s, idx) => (
            <div key={idx} className="schedule-row">
              <div className="sched-date">{s.date}</div>
              <div className="sched-week">{s.week}</div>
              <div className="sched-time">{s.time}</div>
              <div className="sched-remain {s.remain>0 ? '' : 'full'}">
                {s.remain>0 ? `余${s.remain}号` : '余0号'}
              </div>
              <div className="sched-tag">{s.tag}</div>
              {s.remain>0 ? (
                <button className="sched-book" onClick={() => navigate('/confirm-appointment', { state: {
                  doctorName: doctorInfo.doctorName,
                  jobTitle: doctorInfo.jobTitle,
                  hospital: doctorInfo.inauguralHospital,
                  department: '门诊外一科',
                  avatar: doctorInfo.imagePic,
                  fee: Math.min(Number(doctorInfo.servicePrice) || 20, 66),
                  date: s.date,
                  timeRange: s.time === '上午' ? '08:30-12:00(上午)' : '14:00-17:30(下午)'
                } })}>预约</button>
              ) : (
                <button className="sched-book disabled">已约满</button>
              )}
            </div>
          ))}
        </div>

        <div className="schedule-more">
          全部排班 <span>⌄</span>
        </div>
      </div>

      {/* 同科室有号医生推荐（示意） */}
      <div className="info-section recommend-section">
        <h3 className="section-title">同科室有号医生推荐</h3>
        <div className="recommend-grid">
          {(() => {
            // 从头像池中获取真实医生头像
            const loadAvatarPool = (): string[] => {
              try {
                const raw = localStorage.getItem('doctorAvatarPool') || '[]'
                const list = JSON.parse(raw)
                return Array.isArray(list) ? list : []
              } catch { return [] }
            }
            
            const avatarPool = loadAvatarPool()
            const avatar1 = avatarPool[0] || '/doctor-default.svg'
            const avatar2 = avatarPool[1] || '/doctor-default.svg'
            
            return [
              { 
                name: '杨医生', 
                title: '副主任医师',
                avatar: avatar1,
                stats: '好评率 98%'
              },
              { 
                name: '章医生', 
                title: '副主任医师',
                avatar: avatar2,
                stats: '好评率 96%'
              }
            ].map((d, i) => (
              <div key={i} className="rec-card">
                <img 
                  className="rec-avatar" 
                  src={d.avatar} 
                  alt={d.name}
                  onError={(e) => {
                    (e.target as HTMLImageElement).src = '/doctor-default.svg'
                  }}
                />
                <div className="rec-info">
                  <div className="rec-name">{d.name}</div>
                  <div className="rec-title">{d.title}</div>
                  <div className="rec-stats">{d.stats}</div>
                </div>
              </div>
            ))
          })()}
        </div>
      </div>

      {/* 个人简介 */}
      {doctorInfo.personalProfile && (
        <div className="info-section">
          <h3 className="section-title">个人简介</h3>
          <div className="section-content">
            <p>{doctorInfo.personalProfile}</p>
          </div>
        </div>
      )}

      {/* 擅长领域 */}
      {doctorInfo.goodField && (
        <div className="info-section">
          <h3 className="section-title">擅长领域</h3>
          <div className="section-content">
            <p>{doctorInfo.goodField}</p>
          </div>
        </div>
      )}

      {/* 评价统计 */}
      <div className="info-section">
        <h3 className="section-title">评价统计</h3>
        <div className="comment-stats">
          <div className="stat-item">
            <span className="stat-number">{doctorInfo.commentNum}</span>
            <span className="stat-label">总评价</span>
          </div>
          <div className="stat-item">
            <span className="stat-number positive">{doctorInfo.praiseNum}</span>
            <span className="stat-label">好评</span>
          </div>
          <div className="stat-item">
            <span className="stat-number negative">{doctorInfo.badNum}</span>
            <span className="stat-label">差评</span>
          </div>
        </div>
      </div>

      {/* 收到的礼物 */}
      {doctorInfo.doctorReceiveGiftList && doctorInfo.doctorReceiveGiftList.length > 0 && (
        <div className="info-section">
          <h3 className="section-title">收到的礼物</h3>
                     <div className="gifts-grid">
             {doctorInfo.doctorReceiveGiftList.map((gift: DoctorGift, index: number) => (
               <div key={index} className="gift-item">
                <div className="gift-image">
                  <img src={gift.giftPic} alt={gift.giftName} />
                </div>
                <div className="gift-info">
                  <div className="gift-name">{gift.giftName}</div>
                  <div className="gift-worth">价值: {gift.worth}</div>
                  <div className="gift-count">收到: {gift.receiveNum}</div>
                  {gift.meaning && <div className="gift-meaning">{gift.meaning}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 用户评论 */}
      {doctorInfo.commentList && doctorInfo.commentList.length > 0 && (
        <div className="info-section">
          <h3 className="section-title">用户评论</h3>
                     <List className="comment-list">
             {doctorInfo.commentList.map((comment: DoctorComment, index: number) => (
               <List.Item key={index} className="comment-item">
                 <div className="comment-header">
                                       <img
                      src="/doctor-default.svg"
                      alt="用户头像"
                      onError={(e) => {
                        (e.target as HTMLImageElement).src = '/doctor-default.svg'
                      }}
                    />
                   <div className="comment-info">
                     <div className="comment-author">{comment.nickName}</div>
                     <div className="comment-time">{formatTime(comment.commentTime)}</div>
                   </div>
                 </div>
                 <div className="comment-content">
                   {comment.content}
                 </div>
               </List.Item>
            ))}
          </List>
        </div>
      )}
    </div>
  )
}

export default DoctorDetail
